import router from '@/router'
import store from './store'
import nprogress from 'nprogress'
import { Message } from 'element-ui'

let whiteList = ['/login', '/404']
router.beforeEach(async (to, from, next) => {
  nprogress.start()
  if (store.getters.token) {
    if (to.path == '/login') {
      Message.warning('已登陆,无需在登陆!')
      next(from.path)
    } else {
      if (!store.state.user.userInfo.userId) {
        let { roles } = await store.dispatch('user/getUserInfo')
        let result = await store.dispatch('permission/filterRoute', roles.menus)
        router.addRoutes([...result, { path: '*', redirect: '/404', hidden: true }])
        next(to.path)

      } else {
        next()
      }
    }
  } else {
    if (whiteList.indexOf(to.path) != -1) {
      next()
    } else {
      next('/login')
    }
  }
  nprogress.done()

})

router.afterEach((to, from, next) => {
  nprogress.done()
})